class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

// 递归
function invertTree(root: TreeNode | null): TreeNode | null {

    if (!root) return null

    const left = invertTree(root.left)
    const right = invertTree(root.right)
    root.left = right
    root.right = left

    return root
};
// 迭代 使用栈
function invertTree1(root: TreeNode | null): TreeNode | null {
    if (!root) return null
    const stack = [root]
    while (stack.length) {
        const node = stack.pop()
        const left = node!.left
        node!.left = node!.right
        node!.right = left
        if (node!.left) stack.push(node!.left)
        if (node!.right) stack.push(node!.right)
    }
    return root
}
// 迭代 使用队列
function invertTree2(root: TreeNode | null): TreeNode | null {
    if (!root) return null
    const queue = [root]
    while (queue.length) {
        const node = queue.shift()
        const left = node!.left
        node!.left = node!.right
        node!.right = left

        if (node!.left) queue.push(node!.left)
        if (node!.right) queue.push(node!.right)
    }
    return root
}